package com.mingweicai.intergration.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class CountDownLatchTest {

  public static void main(String args[]){

    CountDownLatch countDownLatch = new CountDownLatch(3);

    CountRunnable countRunnable = new CountRunnable(countDownLatch);
    WaitRunnable waitRunnable = new WaitRunnable(countDownLatch);

    Thread threadWait1 = new Thread(waitRunnable);
    threadWait1.setName("Wait1");
    threadWait1.start();

    Thread threadWait2 = new Thread(waitRunnable);
    threadWait2.setName("Wait2");
    threadWait2.start();

    Thread threadA = new Thread(countRunnable);
    threadA.setName("A");
    threadA.start();

    Thread threadB = new Thread(countRunnable);
    threadB.setName("B");
    threadB.start();

    Thread threadC = new Thread(countRunnable);
    threadC.setName("C");
    threadC.start();

  }


  static class CountRunnable implements Runnable{

    CountDownLatch countDownLatch ;

    public CountRunnable(CountDownLatch countDownLatch){
      this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
      System.out.println("Thread countDown start "+Thread.currentThread().getName());
      System.out.println("do my task");
      countDownLatch.countDown();
      System.out.println("Thread countDown end "+Thread.currentThread().getName());
    }

  }

  static class WaitRunnable implements Runnable{

    CountDownLatch countDownLatch ;

    public WaitRunnable(CountDownLatch countDownLatch){
      this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
      try {
        countDownLatch.await();
        System.out.println("It is my trun to excute-----");
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

}
